package com.zhuiyun.project.api.addfriend.service.impl;

import com.zhuiyun.project.api.addfriend.entity.AddFriend;
import com.zhuiyun.project.api.addfriend.mapper.AddFriendMapper;
import com.zhuiyun.project.api.addfriend.model.AppFriendModel;
import com.zhuiyun.project.api.addfriend.service.AddFriendService;
import com.zhuiyun.project.api.appuser.entity.User;

import com.zhuiyun.project.api.appuser.service.AppUserService;
import com.zhuiyun.project.api.friend.entity.Friend;
import com.zhuiyun.project.api.friend.service.FriendService;
import com.zhuiyun.project.api.personmessage.service.PersonMessageService;
import com.zhuiyun.project.common.errorCode.EmErrorCode;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.util.BeanUtils;
import com.zhuiyun.project.util.DateTimeUtils;
import com.zhuiyun.project.util.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName AddServiceImpl
 * @Description TODO
 * @Author kdj
 * @Date 2023/6/20 14:27
 **/
@Service
public class AddFriendServiceImpl implements AddFriendService {
    @Autowired
    private AddFriendMapper addFriendMapper;

    @Autowired
    private AppUserService appUserService;


    @Autowired
    private FriendService friendService;

    @Autowired
    private PersonMessageService personMessageService;

    /**
     * @param appFriendModel
     * @Author kdj
     * @Description 新增添加好友的请求数据
     * @Date 2023/6/21 19:30
     * @Return com.zhuiyun.project.common.response.CommonResult
     */
    @Override
    public CommonResult addFriend(AppFriendModel appFriendModel) {
        //判断数据是否存在
        if (ObjectUtils.isNotEmpty(appFriendModel)) {
            AddFriend addFriend = new AddFriend();
            BeanUtils.copy(appFriendModel, addFriend);
            //判断该用户是否申请过添加好友
            Integer userId = addFriend.getUserId();
            Integer friendId = addFriend.getFriendId();
            AddFriend addFriendBefore = this.getAddByUserIdAndFriendId(userId, friendId);
            //判断 好友有没有添加过我
            AddFriend otherPost = this.getAddByUserIdAndFriendId(friendId, userId);
            //判断数据是否存在
            int i = 0;
            if (!ObjectUtils.isNotEmpty(addFriendBefore)) {
                //新增
                addFriend.setRequestTime(new Date());
                //好友处理状态
                addFriend.setRequestStatus(0);
                addFriend.setRejectionReason(null);
                //默认
                addFriend.setCreateTime(new Date());
                addFriend.setDelFlag(0);
                addFriend.setUpdateTime(new Date());
                i = addFriendMapper.insert(addFriend);
            } else {
                //修改
                addFriendBefore.setRequestStatus(0);
                addFriendBefore.setUserRemarkName(addFriend.getUserRemarkName());
                addFriendBefore.setRequestMessage(addFriend.getRequestMessage());
                addFriendBefore.setUpdateTime(new Date());
                i = addFriendMapper.updateByPrimaryKeySelective(addFriendBefore);
            }
            //判断之前有没有请求过我
            if (ObjectUtils.isNotEmpty(otherPost)) {
                //删除
                otherPost.setDelFlag(1);
                i = addFriendMapper.updateByPrimaryKeySelective(otherPost);
            }
            //修改被请求的未读数
            appUserService.addFriendNewNum(friendId);
            if (i > 0) {
                //添加成功
                return CommonResult.ok();
            } else {
                //添加失败
                return CommonResult.error(EmErrorCode.SAVE_ERROR);
            }
        }
        //参数为空
        return CommonResult.error(EmErrorCode.PARAMETER_VALIDATION_ERROR);
    }

    /**
     * @param userId
     * @param friendId
     * @Author kdj
     * @Description 获取之前有过添加好友请求
     * @Date 2023/6/21 20:17
     * @Return AddFriend
     */
    @Override
    public AddFriend getAddByUserIdAndFriendId(int userId, int friendId) {
        //根据userId和friend查询
        Example example = new Example(AddFriend.class);
        example.createCriteria().andEqualTo("userId", userId).andEqualTo("friendId", friendId).andEqualTo("delFlag", 0);
        return addFriendMapper.selectOneByExample(example);

    }


    /**
     * @param userId
     * @Author kdj
     * @Description 查询我请求过的或者好友请求的数据
     * @Date 2023/6/21 21:07
     * @Return com.zhuiyun.project.common.response.CommonResult
     */
    @Override
    public CommonResult getFriendRequestList(int userId) {
        //判断userId是否数据正确
        if (ObjectUtils.isNotEmpty(userId)) {
            List<Map> mapList = addFriendMapper.getFriendRequestList(userId);
            List<Map> list = mapList.stream().map(map -> {
                Date userBirthday = (Date) map.get("userBirthday");

                Integer age = null;
                if (userBirthday != null) {
                    try {
                        age = DateTimeUtils.getAge(userBirthday);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
                map.put("request", (Long) map.get("request") > 0 ? true : false);
                map.put("age", age);
                return map;
                //如果两个Map的friendId相同且userId也相同，则选择updateTime晚的那个
            }).collect(Collectors.toList());
            return CommonResult.ok(list);
        }//参数为空
        return CommonResult.error(EmErrorCode.PARAMETER_VALIDATION_ERROR);
    }

    /**
     * @param userId
     * @Author kdj
     * @Description 根据userId查询AddFriend数据库
     * @Date 2023/6/21 21:11
     * @Return java.util.List<com.zhuiyun.project.api.addfriend.entity.AddFriend>
     */
    @Override
    public List<AddFriend> getAddFriendByUserId(int userId) {
        Example example = new Example(AddFriend.class);
        example.createCriteria().andEqualTo("userId", userId).andEqualTo("delFlag", 0);
        return addFriendMapper.selectByExample(example);
    }

    /**
     * @param friendId
     * @Author kdj
     * @Description 根据friendId查询AddFriend数据库
     * @Date 2023/6/21 21:11
     * @Return java.util.List<com.zhuiyun.project.api.addfriend.entity.AddFriend>
     */
    @Override
    public List<AddFriend> getAddFriendByFriendId(int friendId) {
        Example example = new Example(AddFriend.class);
        example.createCriteria().andEqualTo("friendId", friendId).andEqualTo("delFlag", 0);
        return addFriendMapper.selectByExample(example);
    }

    /**
     * @param appFriendModel
     * @Author kdj
     * @Description 同意好友添加好友请求
     * @Date 2023/6/23 11:51
     * @Return com.zhuiyun.project.common.response.CommonResult
     */
    @Override
    @Transactional
    public CommonResult addFriendOK(AppFriendModel appFriendModel) {
        //判断元素是否符合
        if (ObjectUtils.isNotEmpty(appFriendModel)) {
            AddFriend addFriend = new AddFriend();
            BeanUtils.copy(appFriendModel, addFriend);
            Example example = new Example(AddFriend.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("userId", addFriend.getUserId()).andEqualTo("friendId", addFriend.getFriendId()).andEqualTo("delFlag", 0);
            //修改数据状态
            addFriend.setRequestStatus(1);
            //修改通过请求时间
            addFriend.setProcessingTime(new Date());
            addFriend.setUpdateTime(new Date());
            int i = addFriendMapper.updateByExampleSelective(addFriend, example);
            //将该条数据查询出来
            AddFriend addFriend1 = addFriendMapper.selectOneByExample(example);
            if (i > 0) {
                //添加好友关系表
                Boolean b = friendService.addFriendByAddFriend(addFriend1);
                if (b) {
                    appUserService.addFriendNewNum(addFriend.getUserId());
                    //发送默认的信息
                    personMessageService.sendFirstMsg(addFriend.getUserId(), addFriend.getFriendId());

                    return CommonResult.ok();
                }
            }
        }
        return CommonResult.error(EmErrorCode.SAVE_ERROR);
    }

    /**
     * @param appFriendModel
     * @Author kdj
     * @Description 拒绝添加好友请求
     * @Date 2023/6/23 16:42
     * @Return com.zhuiyun.project.common.response.CommonResult
     */
    @Override
    public CommonResult addFriendNo(AppFriendModel appFriendModel) {
        if (ObjectUtils.isNotEmpty(appFriendModel)) {
            AddFriend addFriend = new AddFriend();
            BeanUtils.copy(appFriendModel, addFriend);
            Example example = new Example(AddFriend.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("userId", addFriend.getUserId()).andEqualTo("friendId", addFriend.getFriendId()).andEqualTo("delFlag", 0);
            //修改数据状态
            addFriend.setRequestStatus(2);
            //修改处理请求时间
            addFriend.setProcessingTime(new Date());
            addFriend.setUpdateTime(new Date());
            int i = addFriendMapper.updateByExampleSelective(addFriend, example);
            if (i > 0) {
                appUserService.addFriendNewNum(addFriend.getUserId());
                return CommonResult.ok();
            }
        }
        return CommonResult.error(EmErrorCode.SAVE_ERROR);
    }

    /**
     * @param userId
     * @param otherUserId
     * @Author kdj
     * @Description 判断之前是否有过好友请求
     * @Date 2023/7/21 11:10
     * @Return com.zhuiyun.project.common.response.CommonResult
     */
    @Override
    public CommonResult queryAddFriendRecord(int userId, int otherUserId) {
        //判断userId是否数据正确
        if (!ObjectUtils.isNotEmpty(userId) || !ObjectUtils.isNotEmpty(otherUserId)) {
            //参数为空
            return CommonResult.error(EmErrorCode.PARAMETER_VALIDATION_ERROR);
        }

        //返回结果
        Map map = new HashMap<>();
        //判断之前是否有请求过添加好友
        AddFriend userIdPost = getAddByUserIdAndFriendId(userId, otherUserId);
        //判断之前该用户是否有请求过添加好友
        AddFriend otherIdPost = getAddByUserIdAndFriendId(otherUserId, userId);
        if (!ObjectUtils.isNotEmpty(userIdPost) && !ObjectUtils.isNotEmpty(otherIdPost)) {
            //没有请求过
            map.put("status", 3);
            return CommonResult.ok(map);
        }
        //如果 我请求的不为空的话
        if (ObjectUtils.isNotEmpty(userIdPost)) {
            //0 未处理  1 通过 2驳回 3未添加
            map.put("status", userIdPost.getRequestStatus());
            map.put("request", true);
            //如果已经通过判断是否删除好友
            if (userIdPost.getRequestStatus() == 1) {
                List<Friend> friendList = friendService.queryIsFriend(userId, otherUserId);
                if (!ObjectUtils.isNotEmpty(friendList)) {
                    map.put("status", 3);
                    map.remove("request");
                }
            }
            return CommonResult.ok(map);
        } else {
            map.put("status", otherIdPost.getRequestStatus());
            map.put("request", false);
            if (otherIdPost.getRequestStatus() == 1) {
                List<Friend> friendList = friendService.queryIsFriend(userId, otherUserId);
                if (!ObjectUtils.isNotEmpty(friendList)) {
                    map.put("status", 3);
                    map.remove("request");
                }
            }
            return CommonResult.ok(map);
        }
    }
}
